﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace SynoManager.FileStation.Tasks
{
    public class ExtractTask : TaskBase
    {
        private readonly FileInfo file;
        private readonly DirectoryInfo destination;
        private readonly bool overwrite;
        private readonly bool fullPaths;
        private readonly string password;

        public ExtractTask(FileInfo file, DirectoryInfo destination, bool overwrite, bool fullPaths, string password)
        {
            this.file = file;
            this.destination = destination;
            this.overwrite = overwrite;
            this.fullPaths = fullPaths;
            this.password = password;
        }

        public override void Execute()
        {
            Debug.WriteLine("Extracting " + file.RelativePath + " to " + destination.RelativePath, "ExtractTask");

            FileStationClient client = Queue.Service.client;
            var result = client.Extract(destination.RelativePath, (overwrite)?"overwrite":"skip", password, (fullPaths)?"full":"none", file.Path);
            int pid = result.pid;
            Debug.WriteLine("Task sent to device, retrieved pid #" + pid + ", running = " + result.running, "ExtractTask");

            bool isRunning = result.running > 0;
            while (isRunning)
            {
                var progress = client.ReadExtractProgress(pid);
                isRunning = progress.running > 0;

                Debug.WriteLine("#" + pid + " (running = " + progress.running + ")", "ExtractTask");

                if (!isRunning)
                {
                    Thread.Sleep(2000);
                }
            }

            OnCompleted();
        }

        public override string DisplayTitle
        {
            get { return "Unpack " + file.Name; }
        }

        public override string DisplayDescription
        {
            get { return ""; }
        }

        public override System.Drawing.Image DisplayImage
        {
            get { return Properties.Resources.compress; }
        }
    }
}
